package com.pomr.service.synthesize.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pomr.dao.synthesize.ManufacturerDao;
import com.pomr.model.synthesize.Linkman;
import com.pomr.model.synthesize.Manufacturer;
import com.pomr.model.sys.Agency;
import com.pomr.model.sys.User;
import com.pomr.service.synthesize.ManufacturerService;
import com.pomr.util.common.ChineseCharToEn;
import com.pomr.util.page.Page;
@Service
public class ManufacturerServiceImpl implements ManufacturerService {
	@Autowired
	@Qualifier("manufacturerDaoImpl")
	private ManufacturerDao manufacturerDao;

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean saveManufacturer(Manufacturer manufacturer) throws Exception {
		manufacturer.setCreateTime(new Date());
		if(manufacturer.getKjm()==null || "".equals(manufacturer.getKjm())){//没有设置快捷码 默认名称首字母
			manufacturer.setKjm(ChineseCharToEn.getAllFirstLetter(manufacturer.getName()));
		}
		//如果有联系人 同时保存联系人
		Set<Linkman> linkmans = manufacturer.getLinkmans();
		if(linkmans!=null && !linkmans.isEmpty()){
			Iterator<Linkman> itr = linkmans.iterator();
			while(itr.hasNext()){
				Linkman lm = itr.next();
				lm.setAgency(manufacturer.getUser().getAgency());//联系人属于创建者所在机构
				lm.setCreateTime(new Date());
				lm.setUser(manufacturer.getUser());
			}
		}
		return manufacturerDao.add(manufacturer);
	}

	@Override
	public Page<List<Manufacturer>> searchManufacturersByCondition(String name, String email, String tel, String kjm,
			String page, String limit,String bh) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("from Manufacturer ");
		int i=0;
		if(name!=null && !name.equals("")){
			i++;
			sb.append("where name like '%"+name+"%' ");
		}
		if(email!=null && !email.equals("")){
			
			if(i>0){
				sb.append("and ");
			}else{
				sb.append("where ");
			}
			sb.append("email = '"+email+"' ");
			i++;
		}
		if(tel!=null && !tel.equals("")){
			
			if(i>0){
				sb.append("and ");
			}else{
				sb.append("where ");
			}
			sb.append("tel like '%"+tel+"%' ");
			i++;
		}
		if(kjm!=null && !kjm.equals("")){
			if(i>0){
				sb.append("and ");
			}else{
				sb.append("where ");
			}
			sb.append("kjm like '%"+kjm+"%' ");
			i++;
		}
		String hqlStr = sb.toString();
		Page<List<Manufacturer>> p = new Page<List<Manufacturer>>();
		p.setCunrrentPage(Integer.valueOf(page));
		p.setPageSize(Integer.valueOf(limit));
		return manufacturerDao.showPage(hqlStr, "select count(1) "+hqlStr, p);
	}

	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean deleteManufacturersByIds(String[] ids) throws Exception {
		int len = ids.length;
		String id = null;
		System.out.println(len);
		for(int i=0; i<len; i++){
			id = ids[i];
			System.out.println(id);
			if(id!=null && !id.equals("")){
				//TODO 如果存在入库或者其他信息不能删除（外键删除会异常）
				//先删除联系人
				String hqls = "from Manufacturer m left join fetch m.linkmans where m.id="+id;
				Manufacturer m = (Manufacturer) manufacturerDao.findByHql(hqls).get(0);
				if(!manufacturerDao.removeEntity(m)){
					throw new Exception("删除失败，id："+id);
				}else{
					//TODO 删除成功后 先出与之相关联的其他信息
				}
			}
		}
		return true;
	}
	

	@Override
	public Manufacturer searchManufacturerById(String id) throws Exception {
		String hql = "from Manufacturer m left join fetch m.agency where m.id = "+id;
		List<Manufacturer> list = manufacturerDao.findByHql(hql);
		if(list == null || list.size()<=0){
			return null;
		}
		return list.get(0);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean editManufacturerById(Manufacturer manufacturer) throws Exception {
		String hql = "update Manufacturer set name= '"+(manufacturer.getName()==null?"":manufacturer.getName())+"'"+
				",kjm = '"+((manufacturer.getKjm()==null || manufacturer.getKjm().equals(""))?ChineseCharToEn.getAllFirstLetter(manufacturer.getName()):manufacturer.getKjm())+"'"+
				",addr = '"+(manufacturer.getAddr()==null?"":manufacturer.getAddr())+
				"',tel = '"+(manufacturer.getTel()==null?"":manufacturer.getTel())+"',"+
				"email='"+(manufacturer.getEmail()==null?"":manufacturer.getEmail())+
				"',remark='"+(manufacturer.getRemark()==null?"":manufacturer.getRemark())+"'"+
				" where id="+manufacturer.getId();
		if(manufacturerDao.editHql(hql)){
			return true;
		}else{
			throw new Exception("更新厂商信息出错");
		}
	}
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean editManufacturerStatusById(Manufacturer manufacturer) throws Exception {
		String hql = "update Manufacturer set status="+manufacturer.getStatus()+
				" where id="+manufacturer.getId();
		if(manufacturerDao.editHql(hql)){
			return true;
		}else{
			throw new Exception("更新厂商信息出错");
		}
	}

	@Override
	public List<Manufacturer> searchManufacturersOfAgency(User user) throws Exception {
		String hql = "from Manufacturer m where status=null or status!='1'";
		return manufacturerDao.findByHql(hql);
	}

	@Override
	public List<Manufacturer> searchManufacturersByAgency(Agency agency) throws Exception {
		String hql = "from Manufacturer m where (status=null or status!='1') and "+
				"(m.agency.id = "+agency.getId()+" or share='1')";
		return manufacturerDao.findByHql(hql);
	}

}
